package utils

import (
	"encoding/binary"
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"chatroom/common/message"
)

//这里将这些方法关联到结构体中
type TransFer struct {
	//分析应该有那些字段
	Conn net.Conn
	Buf  [8096]byte //这是传输时使用的缓冲

}

func (transFer *TransFer) ReadPkg() (mes message.Message, err error) {

	//buf := make([]byte, 8096)
	fmt.Println("读取客户端发送的数据...")
	//conn.Read 在conn没有被关闭的情况下，才会阻塞
	//如果客户端关闭了，则不会阻塞
	_, err = transFer.Conn.Read(transFer.Buf[:4])
	if err != nil {
		//fmt.Println("readPkg read err=", err)
		//err = errors.New("read pkg header error")
		return
	}
	//fmt.Println("读到的buf=",buf[:4])

	//根据buf[:4] 转成uint32类型
	var pkgLen uint32 = binary.BigEndian.Uint32(transFer.Buf[:4])

	//根据 pkgLen 读取消息内容
	n, err := transFer.Conn.Read(transFer.Buf[:pkgLen])
	if n != int(pkgLen) || err != nil {
		fmt.Println("readPkg body err=", err)
		//err = errors.New("read pkg body error")
		return
	}

	//把 pakLen 反序列化成 -> message.Message
	err = json.Unmarshal(transFer.Buf[:pkgLen], &mes)
	if err != nil {
		err = errors.New("read pkg Umarshal error")
		return
	}

	return

}

func (transFer *TransFer) WritePkg(data []byte) (err error) {

	//先发送一个长度给对方
	var pkgLen uint32 = uint32(len(data))
	//因为 uint 是 4 个字节， 所以此处是[4]byte
	//var buf [4]byte
	binary.BigEndian.PutUint32(transFer.Buf[0:4], pkgLen)
	//发送长度
	n, err := transFer.Conn.Write(transFer.Buf[:4])
	if n != 4 || err != nil {
		fmt.Println("conn.Write111 json.Marshal err=", err)
		return
	}

	//发送 data 数据本身
	n, err = transFer.Conn.Write(data)
	if n != int(pkgLen) || err != nil {
		fmt.Println("conn.Write222 json.Marshal err=", err)
		return
	}

	return
}
